<template>
    <div class="batch-get-inout-container">
        <!-- 搜索筛选区域 -->
        <div class="search-section">
            <p class="section-title">数据筛选</p>
            <el-form :inline="true" :model="data" class="search-form">
                <el-form-item label="出入库单号:" class="form-item">
                    <el-input v-model="data.Name" placeholder="请输入出入库单号" clearable class="custom-input" />
                </el-form-item>

                <el-form-item label="出入库日期:" class="form-item">
                    <div class="date-range">
                        <el-date-picker v-model="data.ReviewInTime" type="date" placeholder="请选择"
                            class="custom-date-picker" />
                        <span class="date-separator">~</span>
                        <el-date-picker v-model="data.ReviewOutTime" type="date" placeholder="请选择"
                            class="custom-date-picker" />
                    </div>
                </el-form-item>

                <el-form-item label="业务类型:" class="form-item">
                    <el-select v-model="data.WarehouseType" placeholder="请选择" clearable class="custom-select"
                        style="width: 120px;">
                        <el-option label="入库" :value="1" />
                        <el-option label="出库" :value="2" />
                    </el-select>
                </el-form-item>

                <el-form-item label="单据时间:" class="form-item">
                    <div class="date-range">
                        <el-date-picker v-model="data.CreateInTime" type="date" placeholder="请选择"
                            class="custom-date-picker" />
                        <span class="date-separator">~</span>
                        <el-date-picker v-model="data.CreateOutTime" type="date" placeholder="请选择"
                            class="custom-date-picker" />
                    </div>
                </el-form-item>

                <el-form-item label="仓库名称:" class="form-item">
                    <el-select v-model="data.Warehouse_ID" placeholder="请选择" clearable class="custom-select"
                        style="width: 120px;">
                        <el-option v-for="item in warehouses" :label="item.warehouse_Name" :value="item.id" />
                    </el-select>
                </el-form-item>

                <el-form-item class="form-item">
                    <div class="button-group">
                        <el-button @click="handleExport" class="export-btn">
                            导出
                        </el-button>
                        <el-button @click="GetBatchInOut" class="refresh-btn">
                            刷新
                        </el-button>
                        <el-button @click="resetForm" class="reset-btn">
                            重置
                        </el-button>
                        <el-button type="primary" @click="GetBatchInOut" class="search-btn">
                            查询
                        </el-button>
                    </div>
                </el-form-item>
            </el-form>
        </div>

        <!-- 数据列表区域 -->
        <div class="table-section">
            <div class="table-header">
                <span class="table-title">数据列表</span>
            </div>
            <el-table :data="tableData" border class="custom-table" style="width: 100%">
                <el-table-column type="index" label="序号" width="60" align="center" />
                <el-table-column prop="warehouseCode" label="出入库单号" width="120" />
                <el-table-column prop="reviewTime" label="出入库日期" width="100">
                    <template #default="scope">
                        <span class="date-text">{{ formatDate(scope.row.reviewTime) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="warehouseName" label="仓库名称" width="100" />
                <el-table-column prop="businessType" label="业务类型" width="80" align="center">
                    <template #default="scope">
                        <el-tag :type="scope.row.businessType === '入库' ? 'success' : 'warning'" size="small">
                            {{ scope.row.businessType }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="outboundQuantity" label="出库数量" width="80" align="center">
                    <template #default="scope">
                        <span v-if="scope.row.businessType === '出库' && scope.row.outboundQuantity > 0"
                            class="quantity-text">
                            {{ scope.row.outboundQuantity }}
                        </span>
                        <span v-else class="empty-text">-</span>
                    </template>
                </el-table-column>
                <el-table-column prop="inboundQuantity" label="入库数量" width="80" align="center">
                    <template #default="scope">
                        <span v-if="scope.row.businessType === '入库' && scope.row.inboundQuantity > 0"
                            class="quantity-text">
                            {{ scope.row.inboundQuantity }}
                        </span>
                        <span v-else class="empty-text">-</span>
                    </template>
                </el-table-column>
                <el-table-column prop="reviewer" label="制单人" width="80" />
                <el-table-column prop="createTime" label="单据时间" width="150">
                    <template #default="scope">
                        <span class="datetime-text">{{ formatDateTime(scope.row.createTime) }}</span>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页区域 -->
        <div class="pagination-section">
            <el-pagination v-model:current-page="data.PageIndex" v-model:page-size="data.PageSize"
                :page-sizes="[10, 20, 25, 30]" :background="true" layout="total, sizes, prev, pager, next, jumper"
                :total="data.Count" next-text="下一页" prev-text="上一页" class="custom-pagination" />
        </div>
    </div>
</template>

<script lang="ts" setup>

import { ElMessage } from 'element-plus'
import { onMounted, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { BasicsRed } from '@/http/axiosHelper'

const route = useRoute()
const tableData = ref([])

const data = ref({
    PageIndex: 1,
    PageSize: 10,
    Batch: null as number | null,
    ProductName: null as number | null,
    Name: '',
    ReviewInTime: '',
    ReviewOutTime: '',
    WarehouseType: null,
    CreateInTime: '',
    CreateOutTime: '',
    Warehouse_ID: null,
    Count: 0
})

const GetBatchInOut = () => {
    BasicsRed.get("api/Workorder/BatchGetInOut", {
        params: {
            PageIndex: data.value.PageIndex,
            PageSize: data.value.PageSize,
            Batch: data.value.Batch,
            ProductName: data.value.ProductName,
            Name: data.value.Name,
            ReviewInTime: data.value.ReviewInTime,
            ReviewOutTime: data.value.ReviewOutTime,
            WarehouseType: data.value.WarehouseType,
            CreateInTime: data.value.CreateInTime,
            CreateOutTime: data.value.CreateOutTime,
            Warehouse_ID: data.value.Warehouse_ID,
        }
    })
        .then(res => {
            tableData.value = res.data.pageData;
            data.value.Count = res.data.totalCount
        })
        .catch(err => {
            console.error("API调用失败:", err)
            ElMessage.error("查询失败，请检查接口地址")
        })
}

// 获取仓库数据
const warehouses = ref<Array<{ warehouse_Name: string, id: number }>>([])
const GetWarehouses = () => {
    BasicsRed.get("api/Inventory/GetWarehouse")
        .then(res => {
            warehouses.value = res.data.data;
        })
}

// 重置表单
const resetForm = () => {
    data.value.Name = ''
    data.value.ReviewInTime = ''
    data.value.ReviewOutTime = ''
    data.value.WarehouseType = null
    data.value.CreateInTime = ''
    data.value.CreateOutTime = ''
    data.value.Warehouse_ID = null
    data.value.PageIndex = 1
    GetBatchInOut()
}

// 导出函数
async function handleExport() {
    try {
        const response = await BasicsRed({
            url: 'api/Workorder/BatchGetInOutExport', // 修正导出接口名称
            method: 'GET',
            params: {
                PageIndex: data.value.PageIndex,
                PageSize: data.value.PageSize,
                Batch: data.value.Batch,
                ProductName: data.value.ProductName,
                Name: data.value.Name,
                ReviewInTime: data.value.ReviewInTime,
                ReviewOutTime: data.value.ReviewOutTime,
                WarehouseType: data.value.WarehouseType,
                CreateInTime: data.value.CreateInTime,
                CreateOutTime: data.value.CreateOutTime,
                Warehouse_ID: data.value.Warehouse_ID,
            },
            responseType: 'blob',
        });

        const fileName = getFileNameFromHeaders(response.headers);
        const blob = new Blob([response.data], {
            type: response.headers['content-type'] || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = fileName;
        document.body.appendChild(a);
        a.click();

        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);

        ElMessage.success('批次出入库数据导出成功')

    } catch (error: any) {
        console.error('导出失败：', error.response?.data || error.message);
        ElMessage.error('导出失败，请检查参数或重新登录');
    }
}

// 辅助函数：从响应头提取文件名
function getFileNameFromHeaders(headers: any) {
    const contentDisposition = headers['content-disposition'] || headers['Content-Disposition'];
    if (!contentDisposition) return '批次出入库记录.xlsx';

    const match = contentDisposition.match(/filename\*?=([^;]+)/);
    if (match) {
        return decodeURIComponent(match[1].replace(/["']/g, ''));
    }
    return '批次出入库记录.xlsx';
}

// 辅助函数：格式化日期
function formatDate(timestamp: string) {
    if (!timestamp) return '';
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

// 辅助函数：格式化日期时间
function formatDateTime(timestamp: string) {
    if (!timestamp) return '';
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

watch(() => { data.value.PageIndex, data.value.PageSize }, () => {
    GetBatchInOut();
}, { deep: true })

onMounted(() => {
    // 从路由参数获取批次和货品名称
    const batch = route.query.batch as string
    const productName = route.query.productName as string

    console.log('接收到的参数:', { batch, productName })

    if (batch) {
        data.value.Batch = parseInt(batch) || null
    }
    if (productName) {
        data.value.ProductName = parseInt(productName) || null
    }

    GetBatchInOut();
    GetWarehouses();
})

</script>

<style scoped>
.batch-get-inout-container {
    padding: 5px;
    background: #f5f5f5;
    min-height: 100vh;
    max-width: 100%;
    margin: 0;
}

/* 搜索区域 */
.search-section {
    background: white;
    padding: 12px;
    margin-bottom: 10px;
    border-radius: 4px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    width: 100%;
}

.section-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin: 0 0 10px 0;
}

.search-form {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    align-items: flex-end;
}

.form-item {
    margin-bottom: 0;
    min-width: 160px;
}

.custom-input,
.custom-select {
    border-radius: 4px;
    min-width: 120px;
}

.date-range {
    display: flex;
    align-items: center;
    gap: 6px;
}

.date-separator {
    color: #666;
    font-weight: 500;
}

.custom-date-picker {
    width: 110px;
}

.range-inputs {
    display: flex;
    align-items: center;
    gap: 6px;
}

.range-separator {
    color: #666;
    font-weight: 500;
}

.range-input {
    width: 80px;
}

.button-group {
    display: flex;
    gap: 8px;
}

.reset-btn {
    background: #f5f5f5;
    border: 1px solid #ddd;
    color: #666;
}

.search-btn {
    background: #67c23a;
    border-color: #67c23a;
}

.export-btn {
    background: #409eff;
    border-color: #409eff;
    color: white;
}

.refresh-btn {
    background: #f5f5f5;
    border: 1px solid #ddd;
    color: #666;
}

/* 表格区域 */
.table-section {
    background: white;
    border-radius: 4px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    margin-bottom: 10px;
    width: 100%;
}

.table-header {
    padding: 10px 12px;
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.table-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
}

/* 表格样式优化 */
.custom-table {
    border-radius: 0;
    width: 100%;
    font-size: 13px;
}

.custom-table :deep(.el-table__header) {
    background: #f8f9fa;
}

.custom-table :deep(.el-table__header th) {
    background: #f8f9fa;
    color: #495057;
    font-weight: 600;
    border-bottom: 1px solid #dee2e6;
    font-size: 13px;
    padding: 8px 4px;
}

.custom-table :deep(.el-table__row) {
    transition: background-color 0.3s ease;
}

.custom-table :deep(.el-table__row:hover) {
    background-color: #f8f9fa;
}

.custom-table :deep(.el-table__cell) {
    padding: 6px 4px;
    font-size: 13px;
}

/* 表格数据样式 */
.date-text {
    font-size: 12px;
    color: #666;
    font-family: 'Courier New', monospace;
}

.datetime-text {
    font-size: 12px;
    color: #666;
    font-family: 'Courier New', monospace;
}

.quantity-text {
    font-weight: 600;
    color: #2c3e50;
    font-size: 12px;
}

.empty-text {
    color: #ccc;
    font-size: 12px;
}

/* 分页区域 */
.pagination-section {
    background: white;
    padding: 12px;
    border-radius: 4px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    text-align: center;
    width: 100%;
}

.custom-pagination :deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
    background: #67c23a;
    color: white;
}

.custom-pagination :deep(.el-pagination.is-background .el-pager li:not(.is-disabled):hover) {
    color: #67c23a;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .batch-get-inout-container {
        padding: 5px;
        max-width: 100%;
    }

    .search-form {
        flex-direction: column;
        align-items: stretch;
    }

    .form-item {
        margin-bottom: 16px;
        min-width: auto;
    }

    .date-range {
        flex-direction: column;
        gap: 8px;
    }

    .custom-date-picker {
        width: 100%;
    }

    .range-inputs {
        flex-direction: column;
        gap: 8px;
    }

    .range-input {
        width: 100%;
    }

    .button-group {
        flex-direction: column;
        align-items: stretch;
    }
}
</style>
